package cn.android.mydata2.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.provider.Settings;
import android.util.Log;

import cn.android.mydata2.dao.TrafficDao;
import cn.android.mydata2.entities.TrafficModel;

/**
 * Created by Administrator on 2016/10/30.
 */

public class TrafficUtils {
    public static String netWorkTypeToString(Context ctx) {
        ConnectivityManager manager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            String type = networkInfo.getTypeName();
            if (type.equalsIgnoreCase("WIFI")) {
                return "wifi";
            } else if (type.equalsIgnoreCase("MOBILE")) {
                String proxyHost = android.net.Proxy.getDefaultHost();
                return "cellular";
            }
        }
        return "noconnect";
    }


    public static void fetchOneAppData(int uid, Context context) {


        TrafficDao dao = new TrafficDao();
        TrafficModel m = dao.getByUid(uid);
        if (m == null) {
            m = new TrafficModel();
            m.setUid(uid);
            m.setCell(0);
            m.setWifi(0);
            m.setTotal(0);
            dao.save(m);
            dao.close();
            return;
        }
        long cellDb = m.getCell();
        long wifiDb = m.getWifi();
        long totalDb = m.getTotal();


        long total = TrafficStats.getUidTxBytes(uid) + TrafficStats.getUidRxBytes(uid);


        if (uid == 10153) {
            total++;
            Log.e("TTT", m.toString());
        }


        if (totalDb == 0) {
            m.setTotal(total);
            dao.save(m);
            dao.close();
            return;
        }

        if (TrafficUtils.netWorkTypeToString(context).equals("wifi")) {
            if (total - totalDb <= 0) {
                m.setWifi(m.getWifi() + total);
                m.setTotal(total);
                dao.save(m);
            } else {
                m.setWifi(m.getWifi() + total - totalDb);
                m.setTotal(total);
            }

            dao.save(m);
            dao.close();

        } else if (TrafficUtils.netWorkTypeToString(context).equals("cellular")) {
            if (total - totalDb < 0) {
                m.setCell(m.getCell() + total);
                m.setTotal(total);
            } else {
                long a = total - totalDb;
                System.out.println(m.getCell() + total - totalDb);
                m.setCell(m.getCell() + total - totalDb);
                m.setTotal(total);
            }
            dao.save(m);
            dao.close();
        }


    }

}
